// Reverse Polish Notation Calculator
// Date 11/10/2018
// By Ben

#include <iostream>
#include <string.h>
#include <stack>

using namespace std;
using std::cout;
using std::endl;
using std::cin;

bool IsNumber(char *src){
	bool isNum = true;

	while (*src){
		if (*src == '.'){
			src++;
		}
		if (!isdigit(*src)){
			isNum = false;
			break;
		}
		src++;
	}
	return isNum;
}

int main(int argc, char *argv[]){
	stack<double>stk;
	double a, b = 0.0;

	string str = "10 30 * 16 - 41 + 25 / 2 *";
	//Show input expression.
	std::cout << "Input  : " << str.c_str() << endl;

	//Split the string
	char *tok = strtok(&str[0], " ");

	//Keep splitting the string
	while (tok != NULL){
		//Output tok element
		//Make sure we have a number to push on the stack.
		if (IsNumber(tok)){
			//Convert char* to double and push onto the stack.
			stk.push(strtod(tok, NULL));
		}
		else{
			//Calc what is on the stack.
			switch (tok[0])
			{
			case '+':
				a = stk.top();
				stk.pop();
				b = stk.top();
				stk.push(a+b);
				break;
			case '-':
				a = stk.top();
				stk.pop();
				b = stk.top();
				stk.push(b-a);
				break;
			case '*':
				a = stk.top();
				stk.pop();
				b = stk.top();
				stk.push(a*b);
				break;
			case '/':
				a = stk.top();
				stk.pop();
				b = stk.top();
				stk.push(b / a);
				break;
			default:
				break;
			}
		}
		//Get next token
		tok = strtok(NULL, " ");
	}
	
	//Show output
	std::cout << "Result : " << (double)stk.top() << endl;

	system("pause");
	return 0;
}